package com.lishe.lishe.lishe.module.me.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lishe.lishe.R;
import com.lishe.lishe.asynchttp.LSWebHelper;
import com.lishe.lishe.lishe.common.AddrBottomDialog;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.me.bean.AdressInfoItem;
import com.lishe.lishe.lishe.module.me.bean.CityItem;
import com.lishe.lishe.lishe.module.me.bean.CountyItem;
import com.lishe.lishe.lishe.module.me.bean.ProvinceItem;
import com.lishe.lishe.lishe.module.me.bean.StreetItem;
import com.lishe.lishe.lishe.module.me.http.HttpUserCenter;
import com.lishe.lishe.lishe.module.me.others.OnAddrSelectedListener;
import com.lishe.lishe.lishe.module.me.selector.AddrSelector;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.ValidationUtils;
import com.smarttop.library.bean.City;
import com.smarttop.library.bean.County;
import com.smarttop.library.bean.Province;
import com.smarttop.library.bean.Street;
import com.smarttop.library.utils.LogUtil;
import com.smarttop.library.widget.AddressSelector;
import com.smarttop.library.widget.OnAddressSelectedListener;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

/**
 * Created by zhcasecom on 2017/8/23.
 */

public class AddAddrActivity extends Activity implements View.OnClickListener, OnAddrSelectedListener, AddrSelector.OnDialogCloseListener {
    private int type = 1;//2修改或1新增收货地址
    private String addrId;
    private String TAG = getClass().getSimpleName();
    private TextView address_edit;
    EditText address_detail_edit, name, mobile;
    List provincelist;
    AddrBottomDialog dialog;
    AddressSelector selector;
    ImageView def_icon;

    Button delete, save;
    boolean isDefalut;
    //完成地址选择保存的地址bean
    ProvinceItem pronvinceItem;
    CityItem cityItem;
    CountyItem countyItem;
    StreetItem streetItem;
    Intent intent = new Intent();

    /**
     * @param activity
     * @param type     //2修改或1新增收货地址
     * @param addrId
     */
    public static void jump(Activity activity, int type, String addrId) {
        Intent intent = new Intent(activity, AddAddrActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("addrId", addrId);
        activity.startActivity(intent);
    }

    public static void jumpForResult(Activity activity, int requstCode, int type, String addrId) {
        Intent intent = new Intent(activity, AddAddrActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("addrId", addrId);
        activity.startActivityForResult(intent, requstCode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_addr);
        Intent intent = getIntent();
        type = intent.getIntExtra("type", 1);
        addrId = intent.getStringExtra("addrId");
        initUI();
        setNav();
        setListner();
//        initSelector();
    }

    private void initSelector() {
        selector = new AddressSelector(AddAddrActivity.this);
        selector.setOnAddressSelectedListener(new OnAddressSelectedListener() {
            @Override
            public void onAddressSelected(Province province, City city, County county, Street street) {

            }
        });

        View view = selector.getView();
    }

    private void initUI() {
        address_edit = findViewById(R.id.address_edit);
        address_detail_edit = findViewById(R.id.address_detail_edit);
        name = findViewById(R.id.recievername);
        mobile = findViewById(R.id.recieverMobile);
        def_icon = findViewById(R.id.def_addr_icon);
        def_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isDefalut = !isDefalut;
                setDefaultAddr(isDefalut);
            }
        });

        delete = findViewById(R.id.delete);
        save = findViewById(R.id.save);
        delete.setOnClickListener(this);
        save.setOnClickListener(this);
        Button back = findViewById(R.id.title_left_button);
        back.setOnClickListener(this);

    }

    private void setListner() {
        address_edit.setOnClickListener(this);

    }

    private void setNav() {
        TextView title = findViewById(R.id.title_text_title);
        if (type == 2) {
            title.setText("编辑收货地址");
            getShopAddressText();

        } else {
            title.setText("新增收货地址");
            Button delete = findViewById(R.id.delete);
            delete.setVisibility(View.GONE);
        }
    }

    public void getShopAddressText() {
        HashMap params = new HashMap();
        params.put("addrId", addrId);

        LSWebHelper.WebCallBack response = new LSWebHelper.WebCallBack() {
            @Override
            public void onSuccess(JSONObject dataJson, String dataString, String message) {
                LoadingUtils.closeDialog();
                Log.e("获取地址信息", dataString);
                String addrInfo = dataJson.optString("addressInfo");
                String privinceInfo = dataJson.optString("privinceInfo");
                String cityInfo = dataJson.optString("cityInfo");
                String countyInfo = dataJson.optString("countyInfo");
                String townInfo = dataJson.optString("townInfo");

                pronvinceItem = JSON.parseObject(privinceInfo, ProvinceItem.class);
                cityItem = JSON.parseObject(cityInfo, CityItem.class);
                countyItem = JSON.parseObject(countyInfo, CountyItem.class);
                if (!townInfo.equals("")) {
                    streetItem = JSON.parseObject(townInfo, StreetItem.class);
                }
                Log.e(TAG, "地址信息" + addrInfo);
                AdressInfoItem item = JSON.parseObject(addrInfo, AdressInfoItem.class);
                setText(item);
            }

            @Override
            public void onFailure(String message) {
                LoadingUtils.closeDialog();
            }
        };
        LoadingUtils.createLoadingDialog(AddAddrActivity.this, "加载中...", true);
        HttpUserCenter.getAddressInfo(params, response);
    }

    private void setText(AdressInfoItem item) {
        name.setText(item.name);
        mobile.setText(item.mobile);
        String addr = item.area;
        addr = addr.replace("/", "");
        addr = addr.substring(0, addr.indexOf(":"));
        address_edit.setText(addr);
        address_detail_edit.setText(item.addr);
        intent.putExtra("address", addr + item.addr);
        if (item.def_addr.equals("1")) {
            setDefaultAddr(true);
            isDefalut = true;
        } else {
            setDefaultAddr(false);
            isDefalut = false;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.address_edit:
                showBottomDialog();
                break;
            case R.id.delete:
                deleteAddress();
                break;
            case R.id.save:
                saveRecieverAddr();
                break;
            case R.id.title_left_button:
                finish();
                break;
        }
    }


//    private void queryArea(int Id, String j_id, String level) {
//        HashMap params = new HashMap();
//        if (j_id != null) {
//            params.put("pId", j_id);
//        }
//        if (level != null) {
//            params.put("level", level);
//        }
//        LSWebHelper.WebCallBack getAreaById = new LSWebHelper.WebCallBack() {
//            @Override
//            public void onSuccess(JSONObject dataJson, String dataString, String message) {
//                String dataStr = dataString;
//                provincelist = JSON.parseArray(dataStr, AreaBean.class);
//                Log.e(TAG, "省份列表" + provincelist);
//            }
//
//            @Override
//            public void onFailure(String message) {
//                Log.e(TAG, message);
//
//            }
//        };
//        HttpUserCenter.getAreaById(params, getAreaById);
//    }

    private void showBottomDialog() {
        dialog = new AddrBottomDialog(AddAddrActivity.this);
        dialog.setOnAddressSelectedListener(this);
        dialog.setDialogDismisListener(this);
        dialog.setTextSize(14);//设置字体的大小
        dialog.setIndicatorBackgroundColor(R.color.color4138);//设置指示器的颜色
        dialog.setTextSelectedColor(R.color.color4138);//设置字体获得焦点的颜色
        dialog.setTextUnSelectedColor(R.color.gray_3);//设置字体没有获得焦点的颜色adi
        dialog.show();

    }


    @Override
    public void dialogclose() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    /**
     * 保存地址信息
     * 此处的ProvinceId等Id对应的是Item的jd_id
     */
    private void saveAddress() {
        HashMap params = new HashMap();
        if (type == 2) {
            params.put("addressId", addrId);
        }
        params.put("userName", name.getText().toString());
        params.put("mobile", mobile.getText().toString());
        params.put("address", address_detail_edit.getText().toString());
        params.put("provinceId", pronvinceItem.jd_id);
        params.put("cityId", cityItem.jd_id);
        if (countyItem != null) {
            params.put("countyId", countyItem.jd_id);
        }else{
            params.put("countyId", "");
        }
        if (streetItem != null) {
            params.put("townId", streetItem.jd_id);
        } else {
            params.put("townId", "");
        }
        params.put("isDefault", checkIsdefault());
        params.put("zipcode", "");
        Log.e(TAG, "params" + params);
        LSWebHelper.WebCallBack saveResponse = new LSWebHelper.WebCallBack() {
            @Override
            public void onSuccess(JSONObject dataJson, String dataString, String message) {
                LoadingUtils.closeDialog();
                setResult(RESULT_OK, intent);
                if (type == 1) {
                    sendUpUIBroadcast();
                }
                finish();
            }

            @Override
            public void onFailure(String message) {
                LoadingUtils.closeDialog();
                Toast.makeText(AddAddrActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        };
        LoadingUtils.createLoadingDialog(AddAddrActivity.this, "请稍候", true);
        HttpUserCenter.saveAddress(params, saveResponse);
    }

    private int checkIsdefault() {
        if (isDefalut) {
            return 1;
        } else return 0;
    }

    /**
     * 判断是否满足条件
     */
    private void saveRecieverAddr() {
        if (!name.getText().toString().equals("")) {
            if (ValidationUtils.isMobileNO(mobile.getText().toString())) {
                if (!address_edit.getText().toString().equals("")) {
                    if (address_detail_edit.getText().toString().length() >= 4) {
                        saveAddress();
                    } else {
                        show("请输入详细地址(不少于4个字)！");
                    }
                } else {
                    show("请选择正确的收货地址！");
                }
            } else {
                show("请填写正确的手机号码！");
            }
        } else {
            show("收货人姓名不能为空！");
        }
    }

    /**
     * 删除地址信息
     */
    private void deleteAddress() {
        HashMap params = new HashMap();
        params.put("addr_id", addrId);
        LSWebHelper.WebCallBack deleteResponse = new LSWebHelper.WebCallBack() {
            @Override
            public void onSuccess(JSONObject dataJson, String dataString, String message) {
                LoadingUtils.closeDialog();
                finish();
            }

            @Override
            public void onFailure(String message) {
                LoadingUtils.closeDialog();
                Toast.makeText(AddAddrActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        };
        LoadingUtils.createLoadingDialog(AddAddrActivity.this, "请稍候", true);
        HttpUserCenter.deleteAddress(params, deleteResponse);

    }

    /**
     * 设置默认地址
     *
     * @param isDefalut
     */
    private void setDefaultAddr(boolean isDefalut) {
        if (isDefalut) {
            def_icon.setImageResource(R.mipmap.sel_choice_icon);
            this.isDefalut = true;
        } else {
            def_icon.setImageResource(R.mipmap.nor_choice_icon);
            this.isDefalut = false;

        }
    }

    private void show(final String tip) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(AddAddrActivity.this, tip, Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public void onAddressSelected(ProvinceItem province, CityItem city, CountyItem county, StreetItem street) {
        String provinceCode = (province == null ? "" : province.code);
        String cityCode = (city == null ? "" : city.code);
        String countyCode = (county == null ? "" : county.code);
        String streetCode = (street == null ? "" : street.code);
        LogUtil.d("数据", "省份id=" + provinceCode);
        LogUtil.d("数据", "城市id=" + cityCode);
        LogUtil.d("数据", "乡镇id=" + countyCode);
        LogUtil.d("数据", "街道id=" + streetCode);
        String s = (province == null ? "" : province.name) + (city == null ? "" : city.name) + (county == null ? "" : county.name) + (street == null ? "" : street.name);
        address_edit.setText(s);
        if (dialog != null) {
            dialog.dismiss();
        }
        pronvinceItem = province;
        cityItem = city;
        countyItem = county;
        streetItem = (street == null ? null : street);
    }

    /**
     * 发送广播通知上一页面更新UI
     */
    private void sendUpUIBroadcast() {
        Intent intent = new Intent();
        intent.setAction(Globals.ACTION_UPADDRESS);
        sendBroadcast(intent);
    }
}
